import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QTextEdit, QMessageBox
from PyQt5 import QtGui
import re
class MyWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        # Create a vertical layout
        layout = QVBoxLayout()
        
        # make a QtFont object
        font = QtGui.QFont("Monaco", 10)
        # Create a label and a line edit for the URL
        curl_lable = QLabel('CURL:')
        self.curl_edit = QTextEdit()
        self.curl_edit.setFont(font)
        #self.curl_edit.setGeometry(100, 200, 280, 280)

        

        # Create a label and a line edit for the headers
        py_lable = QLabel('Python Request:')
        self.py_edit = QTextEdit()
        self.py_edit.setFont(font)

        # Create a button to send the request
        convert_Button = QPushButton('Convert')
        convert_Button.clicked.connect(self.convertRequest)


        #Create a Button to execute the py_edits content
        execute_Button = QPushButton('Execute')
        execute_Button.clicked.connect(self.executeRequest)

        # Add the widgets to the layout
        layout.addWidget(curl_lable)
        layout.addWidget(self.curl_edit)
        layout.addWidget(py_lable)
        layout.addWidget(self.py_edit)
        layout.addWidget(convert_Button)
        layout.addWidget(execute_Button)

        # Set the layout for the window
        self.setLayout(layout)

        # Set the window properties
        self.setGeometry(0, 0, 600, 800)
        self.setWindowTitle('CURL to Python Requests Converter')
        self.show()

    def executeRequest(self):
        py_code = self.py_edit.toPlainText()
        try:
            exec(py_code)
        except Exception as e:
            QMessageBox.critical(self, 'Error', str(e))


    def convertRequest(self):
        curl_code = self.curl_edit.toPlainText()
        # Get the URL and headers from the line edits
        url=re.findall(r'^curl \'(.+)\'',curl_code)
        headers=re.findall(r'-H \'(.*)\'', curl_code)
        data=re.findall(r'--data-raw \'(.*)\'', curl_code)
        if len(url)==0:
            QMessageBox.critical(self, 'Error', 'No URL found')
            return
        if len(headers)==0:
            QMessageBox.critical(self, 'Error', 'No headers found')
            return
        # if len(data)==0:
        #     QMessageBox.critical(self, 'Error', 'No data found')
        #     return
        # Convert the headers to a dictionary
        headers_dict = {}
        for header in headers:
            key, value = header.split(': ', 1)
            headers_dict[key] = value
        # Convert the data to a dictionary
        data_dict={}
        if len(data)>0:
            for pair in data[0].split('&'):
                key, value = pair.split('=', 1)
                data_dict[key.replace('%5B','[').replace('%5D',']')] = value
        
        content="""import requests\nurl = '"""+url[0]+"""'\nheaders = {\n"""
        for key, value in headers_dict.items():
            content+=f"'{key}': '{value}',\n"
        content+="""}\ndata = {"""
        for key, value in data_dict.items():
            content+=f"'{key}': '{value}',"""
        content+="""}\nresponse = requests.post(url, headers=headers, data=data)\nprint(response.status_code)\nprint(response.text)"""
        self.py_edit.setText(content)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    sys.exit(app.exec_())
